var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp();
Page({
  data:{
    applyId:0,
    type:null,
    approvalStatusList:['待审批','审批中','已通过','已驳回','已撤销','已关闭'],
    applyDetail:{},
    approvalList:[],
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '申请单详情', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad(options) {
    this.setData({
      applyId:parseInt(options.id),
      type:options.type
    });
    requestClient = new ZYRequestClient();
  },
  onShow(){
    this.loadApplyDetail();
  },
  loadApplyDetail(){
    var _this = this;
    requestClient.getApplyDetail(_this.data.applyId,function(res){
        if(res.data.data.timeConsume != null){
          res.data.data.timeConsume = _this.formatMinute(res.data.data.timeConsume);
        } else {
          var now = new Date();
          var createTime = new Date(res.data.data.createTime);
          var difftime = (now.getTime() - createTime.getTime()) /1000 /60;
          res.data.data.timeConsume = _this.formatMinute(Math.round(difftime));
        }
        _this.setData({
          applyDetail:res.data.data
        });
        if(res.data.data.approvalList.length > 0){
          var approvalProcessUserList = [];
          // 审批人
          var level = -1;
          var approvalUser = {};
          var aUser = {};
          var userList=[];
          var approvalList = res.data.data.approvalList;
          for(var i = 0; i < approvalList.length; i++){
            var apprUser = approvalList[i];
            // 判断层级
            if(apprUser.level != level){
              // 重置变量
              userList=[];
              aUser = {
                userHeadPortrait:apprUser.userHeadPortrait,
                userName:apprUser.userName,
                handleTime:apprUser.handleTime,
                // result:apprUser.status == 2?'同意':'驳回',
                result:apprUser.opinion,
                timeConsume:_this.formatMinute(apprUser.timeConsume),
              };
              userList.push(aUser);
              approvalUser = {
                approvalType:'approval',
                display:apprUser.display,
                status:apprUser.status,
                title:'审批人',
                userList:userList
              };
              level = apprUser.level;
              approvalProcessUserList.push(approvalUser);
            } else {
              aUser = {
                userHeadPortrait:apprUser.userHeadPortrait,
                userName:apprUser.userName,
                handleTime:apprUser.handleTime,
                // result:apprUser.status == 2?'同意':'驳回',
                result:apprUser.opinion,
                timeConsume:_this.formatMinute(apprUser.timeConsume),
              };
              userList.push(aUser);
              approvalUser.userList = userList;
              approvalProcessUserList[level] = approvalUser;
            }
          }
          // 抄送人
          if(res.data.data.ccList.length > 0){
             var ccList = res.data.data.ccList;
              var ccUserList = [];
              for(var i = 0; i< ccList.length; i ++){
                  var user = ccList[i];
                  var ccUser = {
                    userHeadPortrait:user.userHeadPortrait,
                    userName:user.userName
                  };
                  ccUserList.push(ccUser);
              }
              var approvalCCUser = {
                  approvalType:'user',
                  display:1,
                  title:'抄送人',
                  userList:ccUserList
              };
              approvalProcessUserList.push(approvalCCUser);
          }
          _this.setData({
            approvalProcessUserList:approvalProcessUserList
          });
        }
    })
  },
  bindScanFile(e){
    var fileurl = e.currentTarget.dataset.fileurl;
    // wx.setStorageSync('fileUrl', fileurl);
    // wx.navigateTo({
    //   url: '../filescan/index',
    // })
    if(fileurl){
      wx.showLoading({
        title: '正在加载文档',
        mask:true
      })
      wx.downloadFile({
        url: fileurl,
        success: function (res) {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType:'pdf',
            showMenu:true,
            success: function (res) {
              
            },
            fail:function(f){
              wx.showToast({
                title:'文档打开失败！',
                icon:'error'
              })
            },
            complete:function(c){
              wx.hideLoading({
                success: (res) => {},
              })
            }
          })
        },
        fail:function(f){
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showToast({
            title:'文档下载失败！',
            icon:'error'
          })
        }
      })
    }
  },
  bindScanAttachment(e){
    var _this = this;
    // 存储到本地缓存
    wx.setStorageSync('applyAttachmentList', _this.data.applyDetail.attachmentList);
    // 跳转页面，查看附件
    wx.navigateTo({
      url: '../applyattachment/index',
    })
  },
  // 导出单据
  bindExportApply(e){
    var _this = this;
    wx.showLoading({
      title: '正在导出...',
    })
    requestClient.exportApply(_this.data.applyId,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      const fs = wx.getFileSystemManager();
      fs.writeFile({
        filePath: wx.env.USER_DATA_PATH + "/单据信息.pdf", // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
        data: res.data,
        encoding: "binary", //二进制流文件必须是 binary
        success (res){
          wx.openDocument({ // 打开文档
            filePath: wx.env.USER_DATA_PATH + "/单据信息.pdf",  //拿上面存入的文件路径
            showMenu: true, // 显示右上角菜单
            success: function (res) {
              setTimeout(()=>{wx.hideLoading()},500)
            }
          })
        }
      })
    });
  },
  // 将分钟转化成天，小时，分钟
  formatMinute:function(value){
    var theTime1 = parseInt(value); // 分
    var theTime2 = 0; // 小时
    var theTime3 = 0; // 天
    if(theTime1 > 60) {
      theTime2 = parseInt(theTime1/60);
      theTime1 = parseInt(theTime1%60);
      if(theTime2 > 24){
        //大于24小时
        theTime3 = parseInt(theTime2/24);
        theTime2 = parseInt(theTime2%24);
      }
    }
    var result = '';
    if(theTime1 == 0){
      result = "小于1分钟";
    }
    if(theTime1 > 0) {
      result = ""+parseInt(theTime1)+"分钟"
    }
    if(theTime2 > 0) {
      result = ""+parseInt(theTime2)+"小时"+result
    }
    if(theTime3 > 0) {
      result = ""+parseInt(theTime3)+"天"+result
    }

    return result;
  }
})